package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.adapter.AlramListAdapter;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class AlarmListActivity extends AppCompatActivity {
    public final int CODE_SUCCEED =200;
    private App mApp;
    // 選択済み
    private KidInfoEntity mKidInfoEntity;
    public ParentBleTransfer mParentBleTransfer;
    private List<String> ringtoneList=new ArrayList<>();
    private Map<String,Integer> ringtoneMap=new HashMap<>();
    private int mViewProcess = 0;
    private boolean mUnReceiver = false;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private int mPageCode = PageSerialNumConstants.PAGE_SERIAL_ALARM_SETTING;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "AlarmListActivity_onCreate");
        setContentView(R.layout.activity_alarm_list);
        initReceiver();
        initActivity();
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "AlarmListActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "AlarmListActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                unregisterReceiver(receiver);
                if (mPageJumpFlag) {
                    unregisterReceiver(systemReceiver);
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "AlarmListActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                String message = "編集を再開しています...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmListActivity.this, R.style.commonDlg, message, false);
                mDealWithWaitingDlg.show();
                new BusinessThread(Constants.SEND_KID_IS_USING,
                        mParentBleTransfer,
                        mKidInfoEntity,
                        null,
                        mPageCode).start();
                // ブロードキャストの再登録
                unregisterReceiver(systemReceiver);
                initReceiver();
                mSystemHomeFlag = false;
            }
            mUnReceiver = false;
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "AlarmListActivity_onDestroy");
        super.onDestroy();
        synchronized (mSyncLock) {
            try {
                if (!mUnReceiver) {
                    unregisterReceiver(receiver);
                    if (mPageJumpFlag) {
                        unregisterReceiver(systemReceiver);
                        mPageJumpFlag = false;
                    }
                    mUnReceiver = true;
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }
    private void initActivity() {
        Log.i(TAG, "AlarmListActivity_initActivity");
        TextView textView = (TextView)findViewById(R.id.settingSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);
        getKidRingtoneList();
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        // init
        mApp = (App) getApplication();
        mKidInfoEntity = mApp.findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
    }
    public void backActivity(View view){
        stopPlayRingtone();
        AlarmListActivity.this.finish();
    }
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    switch (mViewProcess) {
                        case Constants.SEND_KID_ENTER:
                            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                                mDealWithWaitingDlg.dismiss();
                            }
                            break;
                    }
                }
            }else if(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)){
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String retStr = bluetoothReceiverDto.getRetStr();
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_GET_RINGTONE.equals(jsonObject.getString("method"))) {
                        JSONArray data=jsonObject.getJSONArray("data");
                        for (int i=0;i<data.length();i++){
                            JSONObject ringtone= data.getJSONObject(i);
                            ringtoneMap.put(ringtone.getString("name"),ringtone.getInt("position"));
                            ringtoneList.add(data.getJSONObject(i).getString("name"));
                        }
                        ListView listview = (ListView)findViewById(R.id.alarmListView);

                        AlramListAdapter listAdapter =
                                new AlramListAdapter(AlarmListActivity.this, R.layout.activity_alarm_list_item,ringtoneList);
                        listAdapter.setmKidInfoEntity(mKidInfoEntity);
                        listAdapter.setmParentBleTransfer(mParentBleTransfer);
                        listAdapter.setRingtoneMap(ringtoneMap);
                        listview .setChoiceMode(ListView. CHOICE_MODE_MULTIPLE);
                        listview.setAdapter(listAdapter);
                        listAdapter.setVoiceName( getIntent().getStringExtra("voiceName"));
                        ImageView submitSetting=findViewById(R.id.submitSetting);
                        submitSetting.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent=new Intent();
//                                System.out.println(listAdapter.getVoiceName());
                                intent.putExtra("voiceName",listAdapter.getVoiceName());//返回值
                                AlarmListActivity.this.setResult(CODE_SUCCEED,intent);//200代表成功
                                AlarmListActivity.this.finish();
                            }
                        });
                    }
                } catch (JSONException e) {
                     Log.e(TAG, e.getMessage());
                }
            }
        }
    };
    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                    if (!mPageJumpFlag) {
                        String message = "編集を再開しています...";
                        mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmListActivity.this, R.style.commonDlg, message, false);
                        mDealWithWaitingDlg.show();
                        mViewProcess = Constants.SEND_KID_IS_USING;
                        new BusinessThread(Constants.SEND_KID_IS_USING, mParentBleTransfer, mKidInfoEntity).start();
                        // ブロードキャストの再登録
                        unregisterReceiver(systemReceiver);
                        initReceiver();
                    }
                }
            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                    mSystemHomeFlag = true;
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                // 初期化
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String macAddress = bluetoothReceiverDto.getAddress();
                if (mApp.isMimamoriCheck(macAddress)) {
                    mApp.addmLsIsMimamori(macAddress);
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                    // ページジャンプ
                    mPageJumpFlag = true;
                    Intent intent1 = new Intent();
                    intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                    intent1.setClass(AlarmListActivity.this, HomeActivity.class);
                    startActivity(intent1);
                } else {
                    mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    ((App) getApplication()).updateKidInfo(mKidInfoEntity);

                    String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                    ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AlarmListActivity.this, R.style.commonDlg, message);
                    processWarringDlg.show();
                    processWarringDlg.setOnOperateSetListener(() -> {
                        processWarringDlg.dismiss();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setClass(AlarmListActivity.this, EditActivity.class);
                        startActivity(intent1);
                    });
                }
            }
        }
    };
    private void getKidRingtoneList() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_RINGTONE);
            jsonObject.put("data", JSONObject.NULL);

            mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
             Log.e(TAG, e.getMessage());
        }
    }
    private void stopPlayRingtone() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "stopPlayRingtone");
            jsonObject.put("data", JSONObject.NULL);

            mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
             Log.e(TAG, e.getMessage());
        }
    }
}
